<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>fileReader</title>
	<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
	<div class="container">
		<div class="page-header">
			To style.
		</div>
		<form>
			<div class="form-group">
				<input class="form-control" type="text" id="path" value="images/">
			</div>
			<div class="form-group">
				<input class="form-control" type="file" id="file" multiple>
			</div>
			<button type="button" id="btn" class="btn btn-default">生成css</button>
			<div class="well" style="margin-top:20px;">
				<pre id="well">.fix_bg{ background-size:100% 100%; display:block;}</pre>
			</div>
		</form>

	</div>

	<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
	<script src="js/filesaver.min.js"></script>
	<script type="text/javascript">
		var $path = $('#path');
		function renderJson(files){
			if(files.length <= 0){
				alert('请选择文件！');
				return false;
			}

			for (var i = 0, f; f = files[i]; i++) {
				console.log(f);
				if (f.type.match('image.*')) {
			        
					var reader = new FileReader();

				      // Closure to capture the file information.
				      reader.onload = (function(theFile) {
				        return function(e) {
				          var img = new Image();
				          img.onload = function(){
				          	$('#well').append("\n." + (theFile.name.substr(0,theFile.name.lastIndexOf("."))) + "{ width:"+ (img.width/100) +"rem; height:"+ img.height/100 +"rem; background-image:url('../images/"+ theFile.name +"');}");
				          };
				          img.src = e.target.result;
				        };
				      })(f);

				      // Read in the image file as a data URL.
				      reader.readAsDataURL(f);

			    }	
			}
		}

		var oDragWrap = document.body;
		//拖进
		oDragWrap.addEventListener('dragenter', function(e) {
		　e.preventDefault();
		}, false);

		//拖离
		oDragWrap.addEventListener('dragleave', function(e) {
		　dragleaveHandler(e);
		}, false);

		//拖来拖去 , 一定要注意dragover事件一定要清除默认事件
		//不然会无法触发后面的drop事件
		oDragWrap.addEventListener('dragover', function(e) {
		　e.preventDefault();
		}, false);

		//扔
		oDragWrap.addEventListener('drop', function(e) {
		　dropHandler(e);
		}, false);

		var dropHandler = function(e) {
			e.preventDefault();

			//获取文件列表
			var files = e.dataTransfer.files;
			//检测是否是拖拽文件到页面的操作
			if (files.length == 0) {return;};
			renderJson(files);		
			// var d = new Date();
			// var blob = new Blob([JSON.stringify(resourceData)], {type: "text/plain;charset=utf-8"});
			// saveAs(blob, "files_"+ d.getTime() +".json");　
			$('#well').html(resourceData);
		}

		$('#btn').click(function(event) {
			var files = document.getElementById("file").files;
			renderJson(files);
			console.log(JSON.stringify(resourceData));
		});
		
	</script>
</body>
</html>